package com.luck.cloud.snowflake;

import com.luck.cloud.configuration.SnowflakeAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 退出的时候主动释放key,避免被占用
 */
@Slf4j
@Component
public class NakeDisposableBean implements DisposableBean {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void destroy() {
        long datacenterId = SnowflakeAutoConfiguration.DATACENTER_ID;
        long workerId = SnowflakeAutoConfiguration.WORKER_ID;
        if (datacenterId != 0 && workerId != 0) {
            String key = SnowflakeAutoConfiguration.SNOWFLAKE_MACHINE_ID_PREFIX + datacenterId + ":" + workerId;
            log.info("    程序退出,清理redis的key:{}", key);
            stringRedisTemplate.delete(key);
        }
    }
}